# Copyright (c) 2005,2006,2007 Dynamic Solutions Inc. (support@dynamic-solutions.com)
#
# This file is part of DataZoomer.
#
# DataZoomer is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# DataZoomer is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


import render
import os
import dzutil
from zoom import zoomer

def load_module(pathname):
    if os.path.isfile(pathname):
        namespace = {
            'zoomer':zoomer,
            'app':zoomer.app,
            'render':render.render,
            'message':dzutil.message,
            'warning':dzutil.warning,
            'url_for':dzutil.url_for,
            'form_for':dzutil.form_for,
            'link_to':dzutil.link_to,
            'redirect_to':dzutil.redirect_to,
            }
        execfile(pathname,namespace)
        return namespace.get('result',None)

def load_controller(controller):

    """Decide which python program is the controller and load it"""
    if controller:
        controller_name = '%s_controller.py' % controller
    else:
        controller_name = 'controller.py'

    pathname = os.path.join(zoomer.app.path,controller_name)
    result = load_module(pathname)
    if result:
        zoomer.debug('controller: %s in %s' % (result.__class__,pathname))
    else:
        zoomer.debug('no controller')
    return result

def dispatch(controller_name=zoomer.webvars.con or None,action_name=zoomer.webvars.action or None):

    def call(controller,action,p):

        zoomer.debug('attempting to call %s.%s' % (controller,action))

        if action:
            handler_name = '_%s'%action
            handler = hasattr(controller,handler_name) and getattr(controller,handler_name) or None
            if handler:
                try:
                    zoomer.debug('calling %s.%s with %s' % (controller,action,p))
                    result = handler(**p)
                except:
                    zoomer.debug('paramters passed to handler: %s' % p)
                    raise
                if result:
                    return result

    """Load the controller to handle the request"""
    controller = load_controller(controller_name)

    if controller:
        """Gather parameters together in preparation for calling methods"""
        p = {}
        button_action = None
        for key in zoomer.webvars.__dict__:
            if key not in ['sid','app','con','action']:
                if key.rsplit('_',1)[-1:][0]=='button':
                    """Only one button action should be able to happen in single a form submission"""
                    button_action = key
                else:
                    p[key] = zoomer.webvars.__dict__[key]

        """If a button has been pressed call the appropriate method"""
        result = \
            call(controller,button_action,p) or \
            call(controller,action_name,p) or \
            call(controller,'index',p)

        if result:
            return result
        else:
            zoomer.debug('no content generated by controller')

